package com.android.danaobank.mvp.fragment;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.danaobank.BuildConfig;
import com.android.danaobank.R;
import com.android.danaobank.adapter.BannerAdAdapter;
import com.android.danaobank.adapter.MallProductListAdapter;
import com.android.danaobank.model.HttpResponse;
import com.android.danaobank.model.response.Advertisement;
import com.android.danaobank.model.response.MallHeadline;
import com.android.danaobank.model.response.MiddleClass;
import com.android.danaobank.model.response.Product;
import com.android.danaobank.model.response.ProductResponse;
import com.android.danaobank.mvp.presenter.GetAdvertisementPresenter;
import com.android.danaobank.mvp.presenter.MallCommentProductPresenter;
import com.android.danaobank.mvp.presenter.MallHeadlinesPresenter;
import com.android.danaobank.mvp.presenter.MallRecommentMiddleClassPresenter;
import com.android.danaobank.mvp.view.GetAdvertisementView;
import com.android.danaobank.mvp.view.MallHeadlinesView;
import com.android.danaobank.utils.AdBannerTransformer;
import com.android.danaobank.utils.EqualsItemDecoration;
import com.android.danaobank.widgets.CustomRefreshLayout;
import com.android.danaobank.widgets.MallIndicator;
import com.android.pdd.baseapp.base.BaseFragment;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.android.material.appbar.AppBarLayout;
import com.lg.meng.BindPresenter;
import com.lg.meng.MessageEvent;
import com.lg.meng.base.BaseSingleListView;
import com.lg.meng.base.IPaginationListView;
import com.youth.banner.Banner;
import com.youth.banner.indicator.RectangleIndicator;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.util.BannerUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.android.danaobank.utils.Constants.MessageCode.MALL_INDEX_LAYOUT_HIDE;
import static com.android.danaobank.utils.Constants.MessageCode.MALL_INDEX_LAYOUT_SHOW;

public class MallRecommendFragment extends BaseFragment implements GetAdvertisementView, MallHeadlinesView, IPaginationListView<HttpResponse<ProductResponse>, Product>,
        BaseSingleListView<HttpResponse<List<MiddleClass>>, MiddleClass> {
    @BindPresenter
    GetAdvertisementPresenter getAdvertisementPresenter;
    @BindPresenter
    MallHeadlinesPresenter mallHeadlinesPresenter;
    @BindPresenter
    MallCommentProductPresenter mallCommentProductPresenter;
    @BindPresenter
    MallRecommentMiddleClassPresenter mallRecommentMiddleClassPresenter;

    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.image_gif)
    ImageView imageView;
    @BindView(R.id.mall_indicator)
    MallIndicator mallIndicator;
    @BindView(R.id.image_headline)
    ImageView imageHeadline;
    @BindView(R.id.title_headline)
    TextView titleHeadline;
    @BindView(R.id.subtitle_headline)
    TextView subtitleHeadline;

    @BindView(R.id.appBarLayout)
    AppBarLayout appBarLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    CustomRefreshLayout refreshLayout;

    @BindView(R.id.layout_headline)
    ViewGroup layoutHeadLine;
    MallProductListAdapter productListAdapter;
    List<Product> productList = new ArrayList<>();

    BannerAdAdapter bannerAdAdapter;

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_mall_recommend;
    }

    @Override
    protected void initViews() {
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);

        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                layoutManager.invalidateSpanAssignments(); //防止第一行到顶部有空白区域
            }
        });
        EqualsItemDecoration decoration = new EqualsItemDecoration(ConvertUtils.dp2px(15), 2);
        decoration.setLayoutType(1);
        recyclerView.addItemDecoration(decoration);
        productListAdapter = new MallProductListAdapter(productList);
        recyclerView.setAdapter(productListAdapter);
        productListAdapter.getLoadMoreModule().setOnLoadMoreListener(() -> {
            mallCommentProductPresenter.loadData();
        });
        productListAdapter.getLoadMoreModule().setAutoLoadMore(true);

        refreshLayout.setOnRefreshListener(() -> {
            initData();
        });

        banner.setPageTransformer(new AdBannerTransformer());
        Glide.with(activity).load(R.mipmap.home_living).into(imageView);

        mallIndicator.setOnItemClickListener((position, middleClass) -> {
            JSONObject paramsObj = getParamsObj(middleClass);
            mallCommentProductPresenter.init(paramsObj);
            mallCommentProductPresenter.refreshData();
        });
        findViewById(R.id.change).setOnClickListener(v -> {
            mallHeadlinesPresenter.loadNext();
        });
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                Log.e("=======verticalOffset", verticalOffset + "");

//                if (appBarLayout.getTotalScrollRange() - Math.abs(verticalOffset) < 20) {
////                    if (isHide) {
////                        EventBus.getDefault().post(new MessageEvent(MALL_INDEX_LAYOUT_HIDE));
////                    }
//                    isHide = false;
//                } else if (Math.abs(verticalOffset) >= 0) {
////                    if (!isHide) {
////                        EventBus.getDefault().post(new MessageEvent(MALL_INDEX_LAYOUT_SHOW));
////                    }
//                    isHide = true;
//                }
                //44dp
                if (appBarLayout.getTotalScrollRange() - Math.abs(verticalOffset) < ConvertUtils.dp2px(44)) {
                    int dx = ConvertUtils.dp2px(44) - appBarLayout.getTotalScrollRange() + Math.abs(verticalOffset);
                    EventBus.getDefault().post(new MessageEvent(MALL_INDEX_LAYOUT_SHOW, dx));
                    isHide = false;
                } else {
                    if (!isHide) {
                        EventBus.getDefault().post(new MessageEvent(MALL_INDEX_LAYOUT_SHOW, 0));
                    }
                    isHide = true;
                }


                if (verticalOffset == 0) {
                    refreshLayout.setCanPull(true);
                } else {
                    refreshLayout.setCanPull(false);
                }
            }
        });

        banner.setIndicator(new RectangleIndicator(getActivity()));
        banner.setIndicatorSpace((int) BannerUtils.dp2px(4));
        banner.setIndicatorRadius(0);
    }

    private boolean isHide;

    @Override
    protected void initData() {
        getAdvertisementPresenter.getAdvertisementByType("mallIndexPosition");
        mallHeadlinesPresenter.loadMallHeadlines();
        mallRecommentMiddleClassPresenter.loadData();
    }

    @Override
    public void getAdvertisementSuccess(List<Advertisement> data) {
        banner.setVisibility(View.VISIBLE);
        bannerAdAdapter = new BannerAdAdapter(data);
        banner.setAdapter(bannerAdAdapter);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(Object data, int position) {
                Advertisement advertisement = bannerAdAdapter.getData(position);
                ToastUtils.showShort("点击了：" + advertisement.getName());
            }
        });
    }

    @Override
    public void getAdvertisementFailed() {

    }

    @Override
    public void loadMallHeadlinesSuccess(MallHeadline mallHeadline) {
        layoutHeadLine.setVisibility(View.VISIBLE);
        titleHeadline.setText(mallHeadline.getName());
        subtitleHeadline.setText(mallHeadline.getMemo());
        Glide.with(activity).load(BuildConfig.IMAGE_BASE + mallHeadline.getImg()).into(imageHeadline);
    }

    @Override
    public void refreshDataSuccess(HttpResponse<ProductResponse> productResponseHttpResponse, List<Product> datas) {
        this.productList.clear();
        this.productList.addAll(datas);
        recyclerView.scrollToPosition(0);
        productListAdapter.notifyDataSet();
        productListAdapter.getLoadMoreModule().loadMoreComplete();
    }

    @Override
    public void loadMoreDataSuccess(HttpResponse<ProductResponse> productResponseHttpResponse, List<Product> datas) {
        this.productList.addAll(datas);
        productListAdapter.notifyDataSet();
        productListAdapter.getLoadMoreModule().loadMoreComplete();
    }

    @Override
    public void dataEmpty() {

    }

    @Override
    public void dataNoMore() {
        productListAdapter.getLoadMoreModule().loadMoreEnd();
    }

    @Override
    public void refreshDataFailed(Throwable e) {
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void loadMoreDataFailed(Throwable e) {
        productListAdapter.getLoadMoreModule().loadMoreFail();
    }

    @Override
    public void loadSingleListSuccess(List<MiddleClass> datas) {
        mallCommentProductPresenter.init(getParamsObj(datas.get(0)));
        mallCommentProductPresenter.refreshData();

        mallIndicator.setVisibility(View.VISIBLE);
        mallIndicator.setMiddleClassList(datas);

        refreshLayout.setRefreshing(false);
    }

    @Override
    public void loadSingleListFailed() {
        refreshLayout.setRefreshing(false);
    }

    private JSONObject getParamsObj(MiddleClass middleClass) {
        JSONObject jsonObject = JSON.parseObject(middleClass.getDescription());
        JSONObject paramsObj = jsonObject.getJSONObject("params");
        paramsObj.put("api_url", jsonObject.getString("url"));
        return paramsObj;
    }

    @OnClick({R.id.btn_more})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_more:
                ToastUtils.showShort("点击了：更多");
                break;
        }
    }
}
